<template>
  <!-- 批量导入销售SKU -->
  <a-modal
    v-model="visibleToSKU"
    cancelText="取消"
    okText="保存"
    title="批量导入SKU"
    width="836px"
    @cancel="closeModel"
    @ok="handleOk('visibleToSKU')"
  >
    <p>
      <a-upload
        name="file"
        :multiple="true"
        :action="baseUrl + '/by-sale-sku/upLoad'"
        :headers="headers"
        @change="handleChange"
      >
        <a-button style="background: #409cff; color: #ffff; border: none">
          <a-icon type="upload" /> 选择上传文件
        </a-button>
      </a-upload>
    </p>
    <a-table
      :columns="columns"
      :data-source="tableDatas"
      :pagination="false"
      :scroll="{ y: 400, x: 770 }"
      bordered
      size="small"
    >
      <span slot="skuAmount" class="action" slot-scope="text, record">
        <a-input
        :maxLength="128"
          v-model="record.skuAmount"
          @change="changeAcuont(record)"
          type="number"
          min="1"
        />
      </span>
      <span slot="skus" class="action" slot-scope="text, record">
        <a-select
          v-model="record.skus"
          show-search
          placeholder="Select a person"
          option-filter-prop="children"
          style="width: 100%"
          :filter-option="filterOption"
          @change="handleChangeSKU"
        >
          <a-select-option
            :value="item.key"
            v-for="item in SKUSelect"
            :key="item.key"
            :records="record"
          >
            {{ item.sku }}
          </a-select-option>
        </a-select>
      </span>
      <span slot="action" class="action" slot-scope="text, record">
        <a-popconfirm
          title="确认删除该条数据吗?"
          ok-text="确认"
          cancel-text="取消"
          @confirm="delRows(record)"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </span>
    </a-table>
  </a-modal>
</template>

<script>
import { SKUSell_page } from "@/apis/clientSide/SKUManage/SKUsell";
// import nanoid from 'nanoid'
import {
  SKUSell_batchSave,
  SKU_select
} from "@/apis/clientSide/SKUManage/SKUsell";
import baseUrl from "@/utils/baseUrl";
export default {
  props: ["getTabSKUsellData"],
  mounted() {
    this.$bus.$off("visibleToSKU");
    this.$bus.$on("visibleToSKU", () => {
      this.visibleToSKU = true;
    });
  },
  created() {
    this.getSKUConut();
  },
  data() {
    return {
      SKUsellData: {
        chineseName: "",
        createBy: 0,
        createTime: "",
        current: 1,
        endTime: "",
        fkList: [
          {
            createBy: 0,
            createTime: "",
            remarks: "",
            revision: 0,
            saleSkuFkId: 0,
            saleSkuId: 0,
            skuAmount: 0,
            skuId: 0,
            tenantId: 0,
            updateBy: 0,
            updateTime: ""
          }
        ],
        remarks: "",
        revision: 0,
        saleSkuCode: "",
        saleSkuId: 0,
        size: 10,
        skuAmount: 0,
        skuId: 0,
        skus: "",
        startTime: "",
        tenantId: 0,
        updateBy: 0,
        updateTime: ""
      },
      isChild: true,
      // sku下拉框
      SKUSelect: [],
      // <!-- 批量导入销售SKU -->
      visibleToSKU: false,
      baseUrl,
      headers: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk")
      },
      tableDatas: [],
      isSkus: true
    };
  },
  methods: {
    //关闭弹窗
    closeModel() {
      this.tableDatas = [];
    },
    //控制最小为1
    changeAcuont(record) {
      console.log(record);
    },
    //模态框确定
    async handleOk() {
      this.isChild = true;
      this.isSkus = true;
      let { responseBody } = await SKUSell_page(this.SKUsellData);
      responseBody.records.forEach(item => {
        this.tableDatas.forEach(val => {
          if (item.saleSkuCode == val.saleSkuCode) {
            this.isChild = false;
          }
        });
      });
      this.tableDatas.forEach(item => {
        if (item.skus == "" || item.skus == null) {
          this.isSkus = false;
        }
      });
      if (!this.isSkus) {
        this.$message.error("请选择系统sku！");
        return false;
      }
      if (this.isChild) {
        let { code } = await SKUSell_batchSave(this.tableDatas);
        if (code === "10000") {
          this.getTabSKUsellData();
          this.visibleToSKU = false;
        }
      } else {
        this.$message.error("不能添加已匹配了的销售SKU");
        return false;
      }
    },
    // 上传文件
    handleChange(info) {
      this.tableDatas = [];
      if (info.fileList.length >= 2) {
        info.fileList = info.fileList.splice(0, 1);
        this.$message.warning("只能上传一个文件！");
      }
      if (info.file.status !== "uploading") {
        if (info.fileList.length > 0) {
          let arr = info.fileList[0].response.responseBody;
          for (let i = 0; i < arr.length; i++) {
            for (let j = i + 1; j < arr.length; j++) {
              if (arr[i].saleSkuCode == arr[j].saleSkuCode) {
                this.$message.error(
                  "上传文件中有重名的销售sku，请修改后再进行提交！"
                );
                info.fileList = [];
                return false;
              }
            }
          }

          this.tableDatas = info.fileList[0]
            ? info.fileList[0].response.responseBody
            : [];
          if (
            info.fileList &&
            info.fileList[0].response.responseBody.length >= 1
          ) {
            info.fileList[0].response.responseBody.forEach((item, i) => {
              item.key = i;
            });
          }
        } else {
          this.tableDatas = [];
        }
      }
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 导入成功`);
      } else if (info.file.status === "error") {
        this.$message.error(`${info.file.name} 导入失败,稍后再试试呢~`);
      }
    },
    //删除每一行
    delRows(record) {
      this.tableDatas.forEach((item, i) => {
        if (record.key === item.key) {
          this.tableDatas.splice(i, 1);
          this.$message.success("删除成功");
        }
      });
    },
    handleChangeSKU(value, option) {
      let { data } = option;
      data.attrs.records.skuId = value;
      // console.log(`selected ${value}`, option);
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    async getSKUConut() {
      let { code, responseBody } = await SKU_select();
      if (code === "200") {
        this.SKUSelect = responseBody;
      }
    }
  },
  computed: {
    columns() {
      return [
        {
          title: "销售SKU",
          dataIndex: "saleSkuCode",
          align: "center",
          // scopedSlots: { customRender: "selfClassifyName" },
          ellipsis: true,
          width: "20%"
        },
        {
          title: "系统SKU",
          dataIndex: "skus",
          align: "center",
          scopedSlots: { customRender: "skus" },
          ellipsis: true,
          width: "20%"
        },
        {
          title: "产品名称",
          dataIndex: "chineseName",
          align: "center",
          width: "20%",
          ellipsis: true,
          scopedSlots: { customRender: "chineseName" }
        },
        {
          title: "数量",
          dataIndex: "skuAmount",
          scopedSlots: { customRender: "skuAmount" },
          align: "center",
          width: "20%",
          ellipsis: true
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 120
        }
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
